package main

import (
	"log"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/jiedan/student-web/server/api"
	"github.com/jiedan/student-web/server/config"
	"github.com/jiedan/student-web/server/middleware"
	"github.com/jiedan/student-web/server/model"
	"github.com/joho/godotenv"
)

func main() {
	// 加载环境变量
	if err := godotenv.Load(); err != nil {
		log.Println("Warning: .env file not found, using environment variables")
	}

	// 初始化数据库连接
	db, err := config.InitDB()
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}

	// 自动迁移数据库表结构
	if err := model.AutoMigrate(db); err != nil {
		log.Fatalf("Failed to migrate database: %v", err)
	}

	// 创建Gin实例
	r := gin.Default()

	// 配置CORS中间件
	r.Use(middleware.CORS())

	// 注册API路由
	api.RegisterRoutes(r, db)

	// 获取服务器端口
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	// 启动服务器
	log.Printf("Server running on port %s", port)
	if err := r.Run(":" + port); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}